import router from '@/router'
import store from '@/store'
import { getToken } from '@/utils/auth' // 验权

const whiteList = ['/login'] // 免登录的路由（白名单）

router.beforeEach((to, from, next) => {
  // 如果有权限

  if (getToken()) {
    if (to.path === '/login') {
      // 有权限之后,不让用户跳登录页
      next({ path: '/' })
    } else {
      // 是否有用户信息，如果没有，需要获取
      if (store.state.login.roles.length === 0) {
        store
          .dispatch('GetUserInfo')
          .then(res => {
            const { roles } = res
            store.dispatch('GenerateRoutes', { roles }).then(addRoutes => {
              router.addRoutes(addRoutes)
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            })
          })
          .catch(error => {
            store.dispatch('FedLogOut').then(() => {
              store.dispatch('openPopup', {
                message: 'Verification failed, please login again'
              })
              next({ path: '/login' })
            })
          })
      } else {
        next()
      }
    }
  } else {
    /* 如果没有token*/
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next({ path: '/login' }) // 否则全部重定向到登录页
    }
  }
})
